package hn.cch.configuration;

import hn.cch.message.response.ExceptionResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.IOException;
import java.sql.SQLException;

@ControllerAdvice
public class ExceptionControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    @ExceptionHandler(value = {IOException.class})
    @ResponseStatus(value = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public ResponseEntity<ExceptionResponse> handleIOException(IOException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        return ResponseEntity.ok(new ExceptionResponse(e.getMessage()));
    }

    @ExceptionHandler(value = {SQLException.class})
    @ResponseStatus(value = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public ResponseEntity<ExceptionResponse> handleSQLException(SQLException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        return ResponseEntity.ok(new ExceptionResponse(e.getMessage()));
    }

}
